/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.model;

import com.caracol.db.AccesoDatos;
import com.caracol.db.CaracolQueryGenerator;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * This class represent the licencia_vehicular table and contains the basic operations (CRUD)
 * @author Roque Rueda
 */
public class LicenciaVehicular {
    
    /**
     * Name of the table in the database
     */
    private static final String TABLE = "licencia_vehicular";
    
    /**
     * Name of the identifier colum in the databse (PK)
     */
    private static final String ID = "id";
    
    /**
     *  Name of the colum num licencia in the databse
     */
    private static final String NUM_LICENCIA = "no_licencia";
    
    /**
     *  Name of the column fecha vencimiento in the database;
     */
    private static final String FECHA_VENCIMIENTO = "fecha_vencimiento";
    
    /**
     *  Number that identifies this instance in the database
     * 
     */
    private int id;
    
    /**
     *  Number of the licence of this instance in the database
     */
    private String numLicencia;
    
    /**
     *  Date in witch this licence expire
     */
    private Date fechaVencimiento;
    
    private static CaracolQueryGenerator caracolQuery = new CaracolQueryGenerator();
    
    /**
     *  Initialize all the values of this instace this constructor should be use only by this class
     * @param id identifier in the database (0 means that is not save in the database)
     * @param numLicencia licence number that is given by a Oficial
     * @param fechaVencimiento expiration date of the licence
     */
    private LicenciaVehicular(int id, String numLicencia, Date fechaVencimiento){
        this.id = id;
        this.numLicencia = numLicencia;
        this.fechaVencimiento = fechaVencimiento;
    }
    
    /**
     *  Initialize an instance of this class with the default values
     */
    public LicenciaVehicular(){
        this(0, "", new Date());
    }
    
    /**
     *  Initialize an instance of this class with all the requiered values in the database
     * @param numLicencia licence number of this instance
     * @param fechaVencimiento expiration date of this licence
     */
    public LicenciaVehicular(String numLicencia, Date fechaVencimiento){
        this(0, numLicencia, fechaVencimiento);
    }
    
    /**
     *  Get's a Licencia Vehicular from the database by it's given id
     * @param id this is the identifier use to search in the database
     * @return the instance if this id is found returns a new instance with the values form the database
     * @throws SQLException if some exception happend during the execution of this operations
     * @throws Exception if something other than the database is throw during the execution of this operation
     */
    public static LicenciaVehicular getLicenciaVehicular(int id) throws SQLException, Exception{
        LicenciaVehicular lv = null;
        String[] columns = new String[] { ID, NUM_LICENCIA, FECHA_VENCIMIENTO };
        
        Map<String, String> where = new LinkedHashMap<String, String>();
        where.put(ID, new Integer(id).toString());
        
        List<Object> rawCargo = caracolQuery.query(columns, TABLE, where, null, null, null, null);
        
        if (rawCargo != null && rawCargo.size() > 0) {
            List<Object> row = (List<Object>) rawCargo.get(0);
            lv  = new LicenciaVehicular();
            lv.id = id;
            lv.setNumLicencia(row.get(1).toString());
            lv.setFechaVencimiento((Date) row.get(2));
        }
        
        return lv;
    }
    
    /**
     *  Get's all the existing Licencia Vehicular rows from the database as a List (ArrayList)
     * @return <code>List</code> of  <code>LicenciaVehicular</code> where each element in the list represent
     * a row from the database
     * @throws SQLException if some exception happend related with the database 
     * @throws Exception if some exeption other than the database
     */
    public static List<LicenciaVehicular> getAll() throws SQLException, Exception{
        ArrayList<LicenciaVehicular> licencias = new ArrayList<LicenciaVehicular>();
        String[] columns = new String[] { ID, NUM_LICENCIA, FECHA_VENCIMIENTO };
        List<Object> rawCargo = caracolQuery.query(columns, TABLE, null, null, null, null, null);
        
        for (Object object : rawCargo) {
            List<Object> row = (List<Object>) object;
            LicenciaVehicular lv = new LicenciaVehicular();
            lv.id = new Double(row.get(0).toString()).intValue();
            lv.setNumLicencia(row.get(1).toString());
            lv.setFechaVencimiento((Date) row.get(2));
            licencias.add(lv);
        }
        
        return licencias;
    }
    
    /**
     * Saves the values of this instance in the database
     * @return true if this operation affects more than 1 row
     * @throws SQLException if some exception related with the database happend
     * @throws Exception if some exception happend
     */
    public boolean save() throws SQLException, Exception {
        if (getId() > 0) { // this is already save no need to continue
            return true;
        }
        Map<String,Object> values = new LinkedHashMap<String,Object>();
        values.put(NUM_LICENCIA, getNumLicencia());
        values.put(FECHA_VENCIMIENTO, getFechaVencimiento());
        
        int rowsAffected = caracolQuery.insert(TABLE, values);
        
        ArrayList<Object> data = null;
        if (rowsAffected > 0) {
            AccesoDatos ad = caracolQuery.getOpenConnection();
            data = new ArrayList<Object>(ad.rawQuery("SELECT currval(\'sqlicencia_vehicular\');")); // get the id
        }
        
        if (data != null && data.size() > 0) {
            ArrayList<Object> row = (ArrayList<Object>) data.get(0);
            Double temp = Double.parseDouble(row.get(0).toString());
            this.id = temp.intValue();
            return true;
        }
        return false;
    }
    
    /**
     * Updates the database with the values of this instance
     * @return true if more than 0 rows are affected by this operation
     * @throws SQLException if some exception related with the database happend
     * @throws Exception if some other exception happend during the excecution of this operation happend
     */
     public boolean update() throws SQLException, Exception {
        int rowsAffected;
        Map<String, Object> values = new LinkedHashMap<String, Object>();
        values.put(NUM_LICENCIA, getNumLicencia());
        values.put(FECHA_VENCIMIENTO, getFechaVencimiento());
        
        Map<String,Object> conditions = new LinkedHashMap<String, Object>();
        conditions.put(ID, getId());
        
        rowsAffected = caracolQuery.update(TABLE, values, conditions);
        
        return rowsAffected > 0;
    }
     
     /**
      * Deletes the entity from the database where it contains the indentifier of this instance
      * @return true if this entity is delete otherwise false
      * @throws SQLException if some database exception happend during the excecution of the operation
      * @throws Exception if some exception happend during the excecution of the operation
      */
     public boolean delete() throws SQLException, Exception {
        if (id <= 0) { // this is already delete
            return true;
        }

        Map<String, Object> conditions = new LinkedHashMap<String, Object>();
        conditions.put(ID, getId());
        int rowsAffected = caracolQuery.delete(TABLE, conditions);

        if (rowsAffected > 0) {
            id = 0;
        }

        return rowsAffected > 0;
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @return the numLicencia
     */
    public String getNumLicencia() {
        return numLicencia;
    }

    /**
     * @param numLicencia the numLicencia to set
     */
    public void setNumLicencia(String numLicencia) {
        this.numLicencia = numLicencia;
    }

    /**
     * @return the fechaVencimiento
     */
    public Date getFechaVencimiento() {
        return fechaVencimiento;
    }

    /**
     * @param fechaVencimiento the fechaVencimiento to set
     */
    public void setFechaVencimiento(Date fechaVencimiento) {
        this.fechaVencimiento = fechaVencimiento;
    }
    
}
